package com.hyb.algorithm.data.struct.str;

/**
 * @author: ybhu
 * @create: 2021/09/25 17:39
 * <p>
 * 8. 字符串转换整数 (atoi)
 * <p>
 * https://leetcode-cn.com/problems/string-to-integer-atoi/
 */
public class StringToIntegerAtoi {

    public int myAtoi(String s) {

        if (s.length() == 0) {
            return 0;
        }

        char[] strArr = s.toCharArray();

        int n = s.length();

        int start = 0;
        int end = n - 1;
        //trim 功能
        while (start < end && strArr[start] <= ' ') {
            start++;
        }

        //trim 功能
        while (end > 0 && strArr[end] <= ' ') {
            end--;
        }

        // 3、如果出现符号字符，仅第 1 个有效，并记录正负
        int sign = 1;
        char first = strArr[start];

        if (first == '+') {
            start++;
        } else if (first == '-') {
            start++;
            sign = -1;
        }

        int ret = 0;
        for (; start <= end; start++) {
            char ch = strArr[start];
            if (ch > '9' || ch < '0') {
                break;
            }


            // 题目中说：环境只能存储 32 位大小的有符号整数，因此，需要提前判：断乘以 10 以后是否越界
            if (ret > Integer.MAX_VALUE / 10 || (ret == Integer.MAX_VALUE / 10 && (ch - '0') > Integer.MAX_VALUE % 10)) {
                return sign * Integer.MAX_VALUE;
            }
            if (ret < Integer.MIN_VALUE / 10 || (ret == Integer.MIN_VALUE / 10 && (ch - '0') > -(Integer.MIN_VALUE % 10))) {
                return sign * Integer.MIN_VALUE;
            }

            ret = 10 * ret + sign * (strArr[start] - '0');
        }

        return ret;

    }
}
